<script lang="ts" setup>
import {
  addParkRent,
  delPark,
  DelRentQ,
  getBuildingList,
  getParkList,
  getRentDetail,
  over,
} from "@/api/park";
import { uploadFile } from "@/api/upload";
import type {
  addRentParams,
  Datum,
  ParkParams,
  ParkPriseRow,
  RentBuilder,
} from "@/types/park";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
} from "element-plus";
import { onMounted, ref, watch } from "vue";

const parkPriseParams = ref<ParkParams>({
  page: 1,
  pageSize: 10,
});
// const parkPriseList = ref<ParkPriseRow[]>([]);
const total = ref<number>();
interface EnterpriseWithRent extends ParkPriseRow {
  // 合同列表
  rentList: Datum[];
}
const parkPriseList = ref<EnterpriseWithRent[]>([]);
// 获取企业prise列表
const getPriseList = async () => {
  const res = await getParkList(parkPriseParams.value);
  // console.log('qiyeghuanlires',res);
  if (res.code === 10000) {
    parkPriseList.value = res.data.rows.map((item) => ({
      ...item,
      rentList: [],
    }));
    total.value = res.data.total;
  }
};
onMounted(() => {
  getPriseList();
});
// 删除prise
const DelPrise = async (id: number) => {
  await delPark(id);
  parkPriseList.value = parkPriseList.value.filter((item) => item.id !== id);
  getPriseList();
  ElMessage.success("删除成功");
};
const dialogVisible = ref(false);
const fileList = ref([]);
// 添加合同
const AddRentParams = ref<Partial<addRentParams>>({
  buildingId: null,
  contractId: null,
  contractUrl: "",
  endTime: "",
  enterpriseId: null,
  startTime: "",
  type: 0,
});
// 打开合同弹窗
const open = (id: number) => {
  dialogVisible.value = true;
  AddRentParams.value.enterpriseId = id;
};

// 合同表单验证
const RentRules = ref<FormRules>({
  buildingId: [{ required: true, message: "请输入租赁楼宇", trigger: "blur" }],
  contractUrl: [{ required: true, message: "请上传租赁合同", trigger: "blur" }],
  endTime: [{ required: true, message: "请输入租赁起止日期", trigger: "blur" }],
});
const addRentRef = ref<FormInstance>();
//  可租赁楼宇列表
const options = ref<RentBuilder[]>([]);
const getRentBuilder = async () => {
  const res = await getBuildingList();
  // console.log('getRentBuilderres',res);
  if (res.code === 10000) {
    options.value = res.data;
  }
};
onMounted(() => {
  getRentBuilder();
});
//  日期选择器
const RentData = ref([]);
watch(RentData, (val) => {
  if (val) {
    AddRentParams.value.startTime = val[0];
    AddRentParams.value.endTime = val[1];
  } else {
    AddRentParams.value.startTime = "";
    AddRentParams.value.endTime = "";
  }
});
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};
// 上传合同
const uploadRent = async (file: UploadRequestOptions) => {
  const fd = new FormData();
  fd.append("file", file.file);
  fd.append("type", "contract");
  const res = await uploadFile(fd);
  // console.log('uploadFileres',res);
  if (res.code === 10000) {
    AddRentParams.value.contractUrl = res.data.url;
    AddRentParams.value.contractId = res.data.id;
    addRentRef.value?.validateField("contractUrl");
    return res.data.url;
  }
};
// 文件大小限制
const beforeUpload = (res: UploadRawFile) => {
  if (res.size > 5 * 1024 * 1024) {
    ElMessage.error("上传文件过大");
  } else {
    ElMessage.success("上传成功");
  }
};
// 删除文件
const DelRent = () => {
  fileList.value = [];
  AddRentParams.value.contractUrl = "";
  AddRentParams.value.contractId = null;
};
const AddPriseRent = async () => {
  await addRentRef.value?.validate();
  await addParkRent(AddRentParams.value as addRentParams);
  ElMessage.success("添加成功");
  dialogVisible.value = false;
};
// 展开行
const onExpandChange = async (row: EnterpriseWithRent) => {
  const res = await getRentDetail(row.id);
  console.log("res", res);
  row.rentList = res.data;
};
const Over = (row: Datum) => {
  ElMessageBox.confirm("当前操作不可逆，确定吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 删除
      await over(row.id);
      row.status = 3;
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
// 删除合同
const Delrent = (son: Datum, father: EnterpriseWithRent) => {
  ElMessageBox.confirm("确定要删除吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 删除
      await DelRentQ(son.id);
      father.rentList = father.rentList.filter(
        (item: Datum) => item.id !== son.id
      );
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="parkPriseParams.name"
      />
      <el-button type="primary" @click="getPriseList">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addRentPrise')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        @expand-change="onExpandChange"
        row-key="id"
        :data="parkPriseList"
      >
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <!-- {{ row }} -->
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime">
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="320">
                <template #default="{ row: Row }">
                  <el-button
                    size="small"
                    type="text"
                    :disabled="row.status !== 3"
                    >续租</el-button
                  >
                  <el-button
                    size="small"
                    type="text"
                    @click="Over(Row)"
                    :disabled="row.status === 3"
                    >退租</el-button
                  >
                  <el-button
                    size="small"
                    type="text"
                    @click="Delrent(Row, row)"
                    :disabled="row.status !== 3"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="320">
          <template #default="{ row }">
            <el-button size="small" type="text" @click="open(row.id)"
              >添加合同</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="$router.push(`/exterpriseDetail/${row.id}`)"
              >查看</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="$router.push(`/addRentPrise/${row.id}`)"
              >编辑</el-button
            >
            <el-button size="small" type="text" @click="DelPrise(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        v-model:current-page="parkPriseParams.page"
        v-model:page-size="parkPriseParams.pageSize"
        :page-sizes="[1, 2, 3, 4]"
        layout="total,sizes, prev, pager, next,jumper"
        :total="total"
        @change="getPriseList"
      />
    </div>
    <!-- 添加合同弹窗 -->
    <div class="dialog-container">
      <el-dialog v-model="dialogVisible" title="添加合同" width="560">
        <div class="form-container">
          <!-- 表单区域 -->
          <el-form
            label-width="400px"
            label-position="top"
            :model="AddRentParams"
            :rules="RentRules"
            ref="addRentRef"
          >
            <el-form-item label="租赁楼宇" prop="buildingId">
              <el-select
                v-model="AddRentParams.buildingId as number"
                placeholder="请选择租赁楼宇"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="租赁起止日期" prop="endTime">
              <el-date-picker
                v-model="RentData"
                type="daterange"
                range-separator="To"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            <el-form-item label="租赁合同" prop="contractUrl">
              <el-upload
                v-model:file-list="fileList"
                :http-request="uploadRent"
                :before-upload="beforeUpload"
                :on-remove="DelRent"
                class="upload-demo"
              >
                <el-button type="primary">Click to upload</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    jpg/png files with a size less than 500KB.
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            {{ AddRentParams }}
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="AddPriseRent"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
